<template>
  <div class="sales-board-wrap table-gl-w">
    <div class="search-w table-filter-form">
      <FilterTable ref="filterTable" :filterItem="filterItem" :isReset="true" @search="searchByVal" />
    </div>
    <a-scrollbar style="flex: 1; overflow-y: auto; height: 100%" v-show="searchParam.startDate">
      <div class="time-w flex-c" v-show="searchParam.startDate">
        <p style="margin-right: 20px">环比周期：{{ targetMap.momStartDate }}至{{ targetMap.momEndDate }}</p>
        <p>年同比周期：{{ targetMap.yoyStartDate }}至{{ targetMap.yoyEndDate }}</p>
      </div>
      <!-- 图表 -->
      <SalesBoardChart ref="boardChartRef" source="user" :targetMap="targetMap" :searchParams="searchParam" />
      <!-- 明细列表 -->
      <SalesBoardChartTableByUser ref="salesBoardChartTable" :searchParams="searchParam" />
    </a-scrollbar>

    <div class="error-w" v-show="!searchParam.startDate">
      <a-empty> 数据量过大，请选择时间缩小查询范围 </a-empty>
    </div>
  </div>
</template>
<script lang="ts" setup>
  import { ref, onMounted, nextTick } from 'vue'
  import { FilterTableItem } from '@/types/components'
  import FilterTable from '@/components/TableFilter.vue'
  import SalesBoardChart from './components/salesBoardChart.vue'
  import SalesBoardChartTableByUser from './components/salesBoardChartTableByUser.vue'
  import { currencySymbol } from '@/utils/globalData'
  import { metricsByUser } from '@/api/dataBoard'
  import { cloneDeep } from 'lodash-es'
  import useBaseDataStore from '@/store/modules/base-data'

  onMounted(() => {
    getUserList()
    getDeptList()
    setDefaultSearch()
  })
  const emit = defineEmits(['toSearch'])
  const props = defineProps({
    searchVal: {
      type: Object,
      default: () => {},
    },
  })

  const filterItem = ref<Array<FilterTableItem>>([
    {
      key: 'deptName',
      label: '部门',
      placeholder: '部门',
      value: ref(),
      type: 'cascader1',
      width: 140,
      optionItems: [],
      attrs: {
        checkStrictly: true,
        fieldNames: { value: 'deptName', label: 'deptName' },
        placeholder: '部门',
        formatLabel: (options: any) => {
          const labels = options.map((option: any) => option.deptName)
          return labels?.[labels.length - 1]
        },
      },
    },
    {
      key: 'operationsName',
      label: '运营',
      value: ref(),
      type: 'select',
      width: 100,
      optionItems: [],
    },
    {
      key: 'currencyCode',
      label: '货币',
      value: ref(props.searchVal.currencyCode),
      type: 'select',
      width: 100,
      optionItems: Object.keys(currencySymbol).map((key: string) => {
        return {
          value: key,
          label: key,
        }
      }),
    },
    {
      type: 'keyword_date_range',
      key: 'UTC',
      keyItems: [
        { label: '汇总日期(0时区)', value: 'UTC' },
        { label: '汇总日期(北京时区)', value: 'CST' },
      ],
      keyWidth: '160',
      value: ref(props.searchVal.startDate ? [props.searchVal.startDate, props.searchVal.endDate] : null),
      placeholder: '请输入',
      label: '汇总日期(0时区)',
      width: 240,
      undeletable: true,
      attrs: {
        placeholder: ['开始日期', '结束日期'],
        allowClear: false,
      },
    },
  ])
  const searchParam = ref<any>({})
  const filterData = ref<any>({})
  const boardChartRef = ref()
  const targetMap = ref<any>({})
  const filterTable = ref()
  const salesBoardChartTable = ref()
  const useBaseData = useBaseDataStore()
  // 获取部门
  async function getDeptList() {
    await useBaseData.getDeptList()
    filterItem.value[0].optionItems = useBaseData.deptList
  }
  // 获取所有用户列表
  async function getUserList() {
    await useBaseData.getUserList()
    filterItem.value[1].optionItems = useBaseData.userList.map((el: any) => {
      return {
        label: el.userName,
        value: el.userName,
      }
    })
  }
  // 初始化查询
  function setDefaultSearch() {
    filterData.value = {
      currencyCode: props.searchVal.currencyCode,
      dataType: props.searchVal.dataType,
      startDate: props.searchVal.startDate,
      endDate: props.searchVal.endDate,
    }
    startSearch()
  }

  function searchByVal(info: any) {
    filterData.value = JSON.parse(JSON.stringify(info)) || {}
    startSearch()
  }

  //查询图表和表格数据
  async function startSearch() {
    searchParam.value = cloneDeep(filterData.value)
    emit('toSearch', filterData.value)
    searchParam.value.shopIds = searchParam.value.shopIds ? searchParam.value.shopIds.split(',') : null
    searchParam.value.timeZone = searchParam.value.dataType
    searchParam.value.currencyCode = searchParam.value.currencyCode || 'USD'
    delete searchParam.value.dataType

    if (!searchParam.value.startDate) return
    getTargetList()
    nextTick(() => {
      boardChartRef.value.refreshData()
      salesBoardChartTable.value.getTableListByVal()
    })
  }
  // 获取所有指标概览数据
  async function getTargetList() {
    const res: any = await metricsByUser(searchParam.value)
    targetMap.value = res?.data || {}
  }
</script>
<style lang="less" scoped>
  .sales-board-wrap {
    height: calc(100vh - @menuAndTabHeight);
    display: flex;
    flex-direction: column;
    overflow: hidden;
  }
  .time-w {
    color: #999;
    padding: 0 15px 10px;
    font-size: 12px;
  }
  .arco-scrollbar {
    flex: 1;
    display: flex;
    flex-direction: column;
    overflow-y: hidden;
    margin-top: 10px;
  }
</style>
